package com.demo;


import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class Demo5 {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
        Student s1 = new Student("汤大为", format.parse("1999-09-05"), 20);
        Student s2 = new Student("公孙雨", format.parse("2000-12-25"), 19);
        Student s3 = new Student("司空瑜", format.parse("2001-05-12"), 18);
        Student s4 = new Student("倪秋雨", format.parse("1998-10-06"), 21);

        ArrayList<Student> stuList = new ArrayList<>();
        stuList.add(s1);
        stuList.add(s2);
        stuList.add(s3);
        stuList.add(s4);

        addStuNum(stuList);
        writeStuToFile(stuList);
    }

    /**
     * 给集合中的学生安排学号
     * @param list
     */
    public static void addStuNum(ArrayList<Student> list){
        int fileLine = getFileLine("./student.txt");

        for (Student student : list) {
            student.setStuNO(
                    "czxy2018" + String.format("%5s\n",fileLine++).replace(" ","0")
            );
        }
    }

    public static int getFileLine(String path){
        try {
            int count = 0;
            BufferedReader reader = new BufferedReader(new FileReader(path));
            while (true){
                String line = reader.readLine();
                if (line == null || line.equals("")){
                    return count;
                }
                count++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 根据格式要求，追加保存集合中的学生到student.txt
     * 数据格式：司徒宁,1999-12-16,20,czxy201800103
     * @param stuList
     */
    private static void writeStuToFile(ArrayList<Student> stuList) {
        try {
            FileOutputStream outputStream = new FileOutputStream("./student.txt",true);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (Student student : stuList) {
                outputStream.write(String.format("%s,%s,%s,%s",
                        student.getStuName(),
                        dateFormat.format(student.getBirthday()),
                        student.getAge(),
                        student.getStuNO()
                        ).getBytes());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
